import type {ActionType, ProColumns} from '@ant-design/pro-components';
import {Form, Space} from 'antd';
import React, {useRef, useState} from 'react';
import {getTableStructUsingPost} from "@/services/easyapi/eDatasource";
import {EditableProTable} from "@ant-design/pro-table";

export type Props = {
  id: number;
  databaseName: string;
  tableName: string;
  outputParams:API.OutputParam[];
  setOutputParams:()=>{};
};


const DynamicTableOutput: React.FC<Props> = (props) => {
  const {databaseName, tableName, id,outputParams,setOutputParams} = props
  const actionRef = useRef<ActionType>();
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [form] = Form.useForm();
  const [tableStructList, setTableStructList] = useState<API.TableStruct[]>([])
  const [selectedValues, setSelectedValues] = useState<string[]>([]); // 已经选择的值
  const [options, setOptions] = useState([]); // 下拉框的选项列表
  const editableFormRef = useRef<any>(); // 创建表格的 form 实例
  const [columnId, setColumnId] = useState<string>()
  const columns: ProColumns<API.OutputParam>[] = [
    {
      title: '参数名称',
      dataIndex: 'paramName',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
      width: '10%',
    },
    {
      title: '绑定字段',
      dataIndex: 'bindField',
      valueType: 'select',
      width: '15%',
      formItemProps: {
        rules: [
          {required: true, message: '请选择绑定字段'}
        ],
      },
      fieldProps: {
        options: options,
        //@ts-ignore
        onChange: (value, option) => {
          // 当用户选择参数名称时，自动填充字段类型
          const selectedColumn = tableStructList.find((item) => item.columnName === value);
          if (selectedColumn) {
            //@ts-ignore
            const key = actionRef.current.editableKeys[0];
            console.log("column===>", selectedColumn)
            editableFormRef.current.setRowData(key, {fieldType: selectedColumn.dataType})
            actionRef.current?.reload()
            setColumnId(key)
          }
        },
      },
    },
    {
      title: '字段类型',
      dataIndex: 'fieldType',
      editable: false,
      render: (_, record) => {
        let key;
        if (record.id) {
          key = record.id
        } else {
          key = columnId;
        }
        // 获取当前行数据的 fieldType
        const rowData = editableFormRef.current?.getRowData(key);
        const fieldType = rowData ? rowData.fieldType : '未选择字段';

        return <span>{fieldType || '未选择字段'}</span>;
      },

      width: '10%',
    },
    {
      title: '说明',
      dataIndex: 'extra',
      valueType: 'text',
      width: '10%',
    },
    {
      title: '操作',
      valueType: 'option',
      width: '10%',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            //@ts-ignore
            action?.startEditable?.(record.id);
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={() => {
            // @ts-ignore
            setOutputParams(outputParams.filter((item) => item.id !== record.id));

            // Optionally remove the corresponding value from selectedValues if needed
            setSelectedValues(selectedValues.filter(value => value !== record.bindField));
          }}
        >
          删除
        </a>,
      ],
    }

  ];


  const fetchTableStructList = async () => {
    const res = await getTableStructUsingPost({
      id: id,
      databaseName: databaseName,
      tableName: tableName,
    });

    if (res.code === 200) {
      //@ts-ignore
      setTableStructList(res.data); // 仍然更新 tableStructList 状态

      // @ts-ignore
      const allOptions = res.data.map((item) => ({
        label: item.columnName,
        value: item.columnName,
      }));

      // 过滤掉已经选择的值
      const filteredOptions = allOptions.filter(
        //@ts-ignore
        (option) => !selectedValues.includes(option.value)
      );
      //@ts-ignore
      setOptions(filteredOptions); // 设置选项
    } else {
      alert('Failed to fetch table structure');
    }
  };

  const coverData = async () => {
    if (options.length === 0) {
      setOptions([]);
    } else {
      const allOptions = tableStructList.map((item) => ({
        label: item.columnName,
        value: item.columnName,
      }));
      alert(selectedValues)
      const filteredOptions = allOptions.filter(
        (option) => !selectedValues.includes(option.value as string)
      );
      //@ts-ignore
      setOptions(filteredOptions)
    }
  }

  return (
    <>
      <Space>
        <>输出参数</>
        <a
          type="primary"
          onClick={() => {
            actionRef.current?.addEditRecord?.({
              id: (Math.random() * 1000000).toFixed(0),
              paramName: '',
              bindField: '',
              fieldType: '',
              extra:''
            });
            if (tableStructList === null || tableStructList.length === 0) {
              fetchTableStructList()
            } else {
              console.log("values====>", selectedValues)
              coverData()
            }
          }}
        >
          新增参数
        </a>
      </Space>
      <EditableProTable<API.OutputParam>
        rowKey="id"
        scroll={{x: 800}}
        actionRef={actionRef}
        maxLength={20}
        // 关闭默认的新建按钮
        recordCreatorProps={false}
        editableFormRef={editableFormRef}
        columns={columns}
        value={outputParams}
        onChange={setOutputParams}
        editable={{
          form,
          editableKeys,
          onSave: async (key, row) => {
            //@ts-ignore
            setSelectedValues([...selectedValues, row.bindField])
            //@ts-ignore
            setOutputParams([...outputParams, row])
          },
          onChange: setEditableRowKeys,
          actionRender: (row, config, dom) => [dom.save, dom.cancel],
        }}
      />
    </>
  );
};

export default DynamicTableOutput;
